﻿/*
 * @author: wizardc
 */

using MessagePack;
using MessagePack.Resolvers;
using UnityEngine;

namespace Dou.Startup
{
    /// <summary>
    /// 
    /// MessagePack 初始化，无需外部调用
    /// 
    /// 为避免生成代码出现打包错误，MessagePack规定只会在运行时中使用，其它情况下的序列化均不允许使用MessagePack
    /// 注：编辑器中可以使用ScriptableObject、Json或其它方式来序列化
    /// 
    /// 生成代码的方式：
    /// 1. Unity 菜单中 Windows-MessagePack-CodeGenerator 打开界面；
    /// 2. 在输入路径中填入（需要绝对路径）：D:\MyProject\Assets
    /// 3. 在输出路径中填入（需要绝对路径）：D:\MyProject\Assets\Scripts\MessagePackGen
    /// 
    /// </summary>
    public class MessagePackStartup
    {
        private static bool _serializerRegistered;

        [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
        public static void Initialize()
        {
            if (_serializerRegistered)
            {
                return;
            }
            _serializerRegistered = true;
            
            StaticCompositeResolver.Instance.Register(
                GeneratedResolver.Instance,
                BuiltinResolver.Instance,
                AttributeFormatterResolver.Instance,
                MessagePack.Unity.UnityResolver.Instance,
                PrimitiveObjectResolver.Instance,
                MessagePack.Unity.Extension.UnityBlitWithPrimitiveArrayResolver.Instance,
                StandardResolver.Instance,
                UnityMathmaticsResolver.Instance
            );
            var options = MessagePackSerializerOptions.Standard;
            options = options.WithCompression(MessagePackCompression.Lz4BlockArray);
            options = options.WithResolver(StaticCompositeResolver.Instance);
            MessagePackSerializer.DefaultOptions = options;
        }

#if UNITY_EDITOR

        [UnityEditor.InitializeOnLoadMethod]
        public static void EditorInitialize()
        {
            Initialize();
        }

#endif
    }
}
